package com.microservice.salmon.oauth.service.rbac.impl;

import com.microservice.salmon.db.entities.ShopMenu;
import com.microservice.salmon.db.entities.ShopRole;
import com.microservice.salmon.db.entities.ShopUser;
import com.microservice.salmon.db.mapper.ShopMenuMapper;
import com.microservice.salmon.db.mapper.ShopRoleMapper;
import com.microservice.salmon.db.mapper.ShopUserMapper;
import com.microservice.salmon.oauth.service.rbac.ShopRbacService;
import com.salmon.common.tree.ITree;
import com.salmon.common.tree.TreeUtils;
import com.salmon.common.utils.JacksonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * <p>
 * RBAC 模型实现类
 * </p>
 *
 * @author 王洪庆 2018-10-30 21:52
 */
@Service
public class ShopRbacServiceImpl implements ShopRbacService {

    @Autowired
    private ShopUserMapper shopUserMapper;

    @Autowired
    private ShopRoleMapper shopRoleMapper;

    @Autowired
    private ShopMenuMapper shopMenuMapper;

    @Override
    public ShopUser obtainShopUser(String loginName) {
        Example example = new Example(ShopUser.class);
        example.excludeProperties("updateTime", "createTime");
        example.createCriteria().andEqualTo("dataFlag", Byte.valueOf("1"))
                                .andEqualTo("loginName", loginName);
        return shopUserMapper.selectOneByExample(example);
    }

    @Override
    public ShopRole obtainShopRoleByRoleId(Integer roleId) {
        return shopRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public List<ITree> obtainTreeMenu(Integer roleId, Integer shopId) {
        return TreeUtils.getTreeList(obtainShopMenu(roleId, shopId));
    }

    @Override
    public List<ShopMenu> obtainShopMenu(Integer roleId, Integer shopId) {
        if(roleId == 0) { // 查询所有的菜单
            Example example = new Example(ShopMenu.class);
            example.selectProperties("id", "parentId", "name", "href", "target", "icon", "permission");
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("dataFlag", Byte.valueOf("1"))
                    .andEqualTo("isShow", Byte.valueOf("1"));
            example.orderBy("menuSort").asc();
            return shopMenuMapper.selectByExample(example);
        } else { // 查询已经保存权限的菜单
            Example example = new Example(ShopRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("dataFlag", Byte.valueOf("1"))
                    .andEqualTo("shopId", shopId)
                    .andEqualTo("id", roleId);
            ShopRole shopRole = shopRoleMapper.selectOneByExample(example);
            return JacksonUtils.jsonToList(shopRole.getPrivilege(), ShopMenu.class);
        }
    }
}
